package com.windchime.blog.controller;

import com.github.pagehelper.PageInfo;
import com.windchime.blog.entity.Blog;
import com.windchime.blog.entity.Tag;
import com.windchime.blog.service.BlogService;
import com.windchime.blog.service.TagService;
import com.windchime.blog.service.TypeService;
import com.windchime.blog.utils.StringSplitUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.stream.Collectors;

@Controller
public class FrontTagController {

    @Autowired
    private TagService tagService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    /**
     * 标签页
     * @param model 传值
     * @param page 当前页
     * @param id 标签ID
     * @return tags
     */
    @GetMapping("/tags")
    public String tags(Model model, @RequestParam(defaultValue = "1", value = "page") Integer page, @RequestParam Integer id) {
        Tag tag = tagService.getById(id);
        model.addAttribute("tagName", tag.getName());
        model.addAttribute("activeTagId", id);

        //设置每个分类ID下的博客
        Integer limit = 5;
        PageInfo<Blog> blogs = blogService.selectBlogListByTagId(page, limit, id);
        for (Blog blog : blogs.getList()) {
            /*
                设置该博客有什么标签
            */
            List<Long> tagIdList = StringSplitUtil.split(blog.getTagIds(), ",");
            List<Tag> tags = tagIdList.stream().map(tagId -> tagService.getById(tagId)).collect(Collectors.toList());
            blog.setTags(tags);

            blog.setTypeName(typeService.getById(blog.getTypeId()).getName());
        }
        model.addAttribute("blogs", blogs);

        return "/tags";
    }

}
